<template>
  <div>
    <el-card shadow="hover">
      <!-- 添加按钮 -->
      <el-button
        type="primary"
        size="default"
        :icon="Plus"
        @click="addTrademark"
        v-hidden="'btn.Trademark.add'"
        >添加</el-button
      >

      <!-- 列表 -->
      <el-table
        border
        style="margin-top: 20px"
        :data="trademarkList.records"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" align="center" :width="80">
        </el-table-column>
        <el-table-column prop="tmName" label="品牌名称"> </el-table-column>
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <img :src="row.logoUrl" alt="" style="width: 100px; height: 80px" />
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template #="{ row, $index }">
            <el-button
              type="warning"
              size="default"
              :icon="Edit"
              @click="UpdateTrademark(row)"
              v-hidden="'btn.Trademark.update'"
            ></el-button>
            <el-popconfirm
              :title="`确定要删除${row.tmName}吗？`"
              @confirm="delateTrademark(row)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  size="default"
                  :icon="Delete"
                  v-hidden="'btn.Trademark.remove'"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <el-pagination
        style="margin-top: 20px"
        @size-change="sizeChange"
        @current-change="getTrademarkList"
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7]"
        :total="trademarkList.total"
        background
        :pager-count="7"
        layout=" prev, pager, next, jumper, ->, sizes, total"
      >
      </el-pagination>

      <!-- 对话框 -->
      <el-dialog
        v-model="dialogFormVisible"
        :title="trademarkParams.id ? '更新品牌' : '添加品牌'"
        width="25%"
      >
        <el-form
          label-width="90px"
          :model="trademarkParams"
          :rules="rules"
          ref="formRef"
        >
          <el-form-item label="品牌名称" prop="tmName">
            <el-input autocomplete="off" v-model="trademarkParams.tmName" />
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="trademarkParams.logoUrl"
                :src="trademarkParams.logoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addOrUpdateTrademark"
              >确定</el-button
            >
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {
  name: "Trademark",
};
</script>

<script lang="ts" setup>
import type { UploadProps, FormRules, FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { Plus, Edit, Delete } from "@element-plus/icons-vue";
import { ref, onMounted, reactive, nextTick } from "vue";

import {
  reqTrademarkList,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/product/trademark"; // 请求函数
import type { ITrademarkList, IBrand } from "@/api/product/trademark/model"; // 数据类型

const currentPage = ref<number>(1); // 分页器第几页
const pageSize = ref<number>(3); // 每页显示几条
const loading = ref<boolean>(false); // loading状态
const dialogFormVisible = ref<boolean>(false); // 对话框状态
const formRef = ref<FormInstance>(); // form表单对象

// 分页数据
const trademarkList = reactive<ITrademarkList>({
  records: [],
  total: 0,
});

// 新增或修改品牌的参数
const trademarkParams = reactive<IBrand>({
  tmName: "",
  logoUrl: "",
});

// 获取品牌数据 及 更改当前页获取数据
const getTrademarkList = async (page: number = 1) => {
  loading.value = true;
  currentPage.value = page;
  let result = await reqTrademarkList(currentPage.value, pageSize.value);
  trademarkList.total = result.total;
  trademarkList.records = result.records;
  loading.value = false;
};

// 更改每页显示几条获取数据
const sizeChange = (limit: number) => {
  pageSize.value = limit;
  getTrademarkList();
};

// 文件(图片)上传成功时的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  trademarkParams.logoUrl = response.data;
};

// 文件(图片)之前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/png" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 <= 5) {
      return true;
    }
  } else {
    return false;
  }
};

// 提交添加确定按钮的回调
const addOrUpdateTrademark = () => {
  formRef.value?.validate(async (isValid: boolean) => {
    if (isValid) {
      try {
        await reqAddOrUpdateTrademark(trademarkParams);

        dialogFormVisible.value = false;

        ElMessage({
          message: trademarkParams.id ? "更新品牌成功" : "添加品牌成功",
          type: "success",
        });

        getTrademarkList(trademarkParams.id ? currentPage.value : 1);
      } catch (error) {
        ElMessage({
          message: "添加失败",
          type: "error",
        });
      }
    } else {
      ElMessage({
        message: "数据校验失败",
        type: "error",
      });
    }
  });
};

// 自定义tmName的校验规则
const validatePass = (rule: any, value: any, callback: any) => {
  if (
    /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/.test(
      value
    )
  ) {
    callback();
  } else {
    callback(new Error("品牌名字必须大于二"));
  }
};

// 表单校验规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "必须输入品牌名称", trigger: "blur" },
    { required: true, validator: validatePass, trigger: "blur" },
  ],
  logoUrl: [{ required: true, message: "必须上传图片" }],
});

// 添加按钮的回调
const addTrademark = () => {
  dialogFormVisible.value = true;
  trademarkParams.logoUrl = "";
  trademarkParams.tmName = "";
  trademarkParams.id = "";
  nextTick(() => {
    formRef.value?.resetFields();
  });
};

// 修改品牌按钮的回调
const UpdateTrademark = (row: IBrand) => {
  dialogFormVisible.value = true;

  nextTick(() => {
    formRef.value?.resetFields();
    trademarkParams.id = row.id;
    trademarkParams.logoUrl = row.logoUrl;
    trademarkParams.tmName = row.tmName;
  });
};

// 确定删除品牌的回调
const delateTrademark = async (row: IBrand) => {
  try {
    await reqDeleteTrademark(row.id);

    getTrademarkList(currentPage.value);
    ElMessage({
      type: "success",
      message: `删除${row.tmName}成功`,
    });
  } catch (error) {
    ElMessage({
      type: "error",
      message: `删除${row.tmName}失败`,
    });
  }
};

onMounted(() => {
  getTrademarkList();
});
</script>

<style scoped>
.el-button--text {
  margin-right: 15px;
}
.el-select {
  width: 300px;
}
.el-input {
  width: 300px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
